#include "head_c.h"
#include <termio.h>


int main(){
    char ip[100] = "\0";
    getparameter("ip", ip);

    char port[100] = "\0";
    getparameter("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    //LOG_WRITE(LOG_DEBUG, "client.c 15hang\n");

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    int ret = connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    ERROR_CHECK(ret, -1, "connect");
    //初始化用户状态
    user_t status;
    memset(&status, 0, sizeof(status));

    //初始化自定义协议
    portocol_t portocol;

    LOG_WRITE(LOG_DEBUG, "日志等级LOG_DEBUG");
    LOG_WRITE(LOG_ERROR, "日志等级LOG_ERROR");
    for (;;)
    {   
        fflush(stdout);
        memset(&portocol, 0, sizeof(portocol));

        if (status.is_login == false)
        {
            printf("[1]登录     [2]注册     [3]退出\n");
            read_stdin(&status, &portocol, socket_fd);
            switch (portocol.cmd)
            {
            case LOGIN:
                login(&status, &portocol, socket_fd);
                break;
            case REGISTER:
                regist(&status, &portocol, socket_fd);
                break;
            case EXIT:

                printf("欢迎下次使用\n");
                exit(0);
            }
        }
        else
        {
            usleep(300);
            printf("%s@: ", status.user_name);
            fflush(stdout);
            read_stdin(&status, &portocol, socket_fd);

            switch (portocol.cmd)
            {
            case CD:
                cd(&status, &portocol, socket_fd);
                break;
            case LS:
                ls(&status, &portocol, socket_fd);
                break;
            case PUTS:
                do_puts(&portocol);
                //upload(&status, &portocol, socket_fd);
                break;
            case GETS:
                //printf("client: arg = %s\n", portocol.arg);
                do_gets(&portocol);
                //download(&status, &portocol, socket_fd);
                break;
            case RM:
                rm(&status, &portocol, socket_fd);
                break;
            case PWD:
                pwd(&status, &portocol, socket_fd);
                break;
            case MKDIR:
                create_dir(&status, &portocol, socket_fd);
                break;
            default:
                printf("输入命令有误，请重新输入！\n");
            }
        }

    }

    close(socket_fd);
    return 0;
}

